#include <iostream>
#include <stdio.h>
// #include<cstdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <thread>
#include <mutex>
#include <netdb.h>
#include <cstring>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <cstring>

using namespace std;

int main(int argc, char **argv)
{

    sockaddr_in seraddr, clientaddr;
    // socklen_t seraddr_len, cliaddr_len;

    // seraddr_len = sizeof(seraddr);
    // cliaddr_len = sizeof(clientaddr);

    char serip[] = "127.0.0.1";
    // int port = 3333;
    char port[] = "3333";

    char buf[1024];
    // int buflen = sizeof(buf);

    int sfd = socket(AF_INET, SOCK_STREAM, 0);
    seraddr.sin_family = AF_INET;
    seraddr.sin_port = htons(atoi(port));
    seraddr.sin_addr.s_addr = inet_addr(serip);

    bind(sfd, (struct sockaddr *)&seraddr, sizeof(seraddr));
    listen(sfd, 1024);
    cout<<"服务器启动，端口："<<port<<endl;

    socklen_t clientlen = sizeof(clientaddr);
    int cfd = accept(sfd, (struct sockaddr *)&clientaddr, &clientlen);

    // memset(&buf, 0, buflen);
    sprintf(buf, "%s", "Welcom to server...\n");
    send(cfd, buf, sizeof(buf), 0);

    for (size_t i = 0; i < 3; i++)
    {
        bzero(&buf, sizeof(buf));
        recv(cfd, &buf, sizeof(buf), 0);
        printf("服务器收到的信息：%s", buf);

        bzero(&buf, sizeof(buf));
        sprintf(buf, "%s%ld", "server send message to client ", i);
        send(cfd, &buf, sizeof(buf), 0);
    }
    cout << "服务器结束..." << endl;
    close(sfd);

    return 0;
}